package com.study4j.common.exception;

import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;

import com.study4j.common.enums.EnumSysCode;
import com.study4j.common.model.ResultModel;
import com.study4j.common.utils.RespUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * @author jiangbin
 * @description 全局异常处理
 */
@Slf4j
public class GlobalExcptionHandler {

    /**
     * @description 参数验证异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(BindException.class)
    public ResultModel validExceptionHandler(BindException e) {
        log.error(e.getMessage(), e);
        StringBuilder errorStr = new StringBuilder();
        e.getBindingResult().getFieldErrors().forEach(error -> {
            errorStr.append(error.getField() + ":" + error.getDefaultMessage());
            log.error(error.getField() + ":" + error.getDefaultMessage());
        });

        ResultModel resultModel = new ResultModel();
        resultModel.setMessage(errorStr.toString());
        resultModel.setCode(EnumSysCode.PARAMETER_ERR.getCode());
        return resultModel;
    }

    @ExceptionHandler(value = {ServerException.class})
    public ResultModel serverExceptionHandler(ServerException e) {
        log.error(e.getMessage(), e);
        return RespUtil.result(e.getCode(), null);
    }

    @ExceptionHandler(value = {Exception.class})
    public ResultModel excptionHandler(Exception e) {
        log.error(e.getMessage(), e);
        return RespUtil.error(e);
    }
}
